﻿(function( $){

	$.fn.scrollPagination = function(options) {

		var opts = $.extend({},$.fn.scrollPagination.defaults, options);  
		var target = opts.scrollTarget;
		if (target == null) target = obj;
		opts.scrollTarget = target;

		return this.each(function() {
			$.fn.scrollPagination.init($(this), opts);
		});

	};

	$.fn.stopScrollPagination = function(){
		return this.each(function() {
			$(this).attr('scrollPagination', 'disabled');
		});
	};

	$.fn.setScrollPagination = function(pageIndex,totalItems){
		if(typeof pageIndex === 'object'){
			var obj = pageIndex || {};
			pageIndex = obj.pageIndex;
			totalItems = obj.totalItems;
		}
		return this.each(function() {
			typeof pageIndex === 'number' && $(this).attr('pageIndex',pageIndex);
			typeof totalItems === 'number' && $(this).attr('totalItems',totalItems);
		});
	};

	$.fn.scrollPagination.loadContent = function(obj, opts, isInit){
		var target = opts.scrollTarget,
			page = opts.scrollPage,
			vertical = opts.vertical;
		var mayLoadContent = $(target)[vertical ? 'scrollTop' : 'scrollLeft']() + opts.offset >= $(page)[vertical ? 'outerHeight' : 'outerWidth'](true) - $(target)[vertical ? 'outerHeight' : 'outerWidth'](true);
		if (isInit || mayLoadContent){
			var pageIndex = parseInt($(obj).attr('pageIndex')),
				//totalItems = parseInt($(obj).attr('totalItems')),
				//pageCount = Math.ceil(totalItems / opts.pageSize), //向上取整，有小数就整数部分加1
			url = typeof opts.url === 'function' ? opts.url(pageIndex) : opts.url;
            var pageCount = 0; //初始化
			var ajaxCallback = function(data){
				opts.afterLoad && opts.afterLoad(data,pageIndex,pageCount);
                //从数据库中获取
                pageCount = data.totalPage;//Math.ceil(totalItems / opts.pageSize), //向上取整，有小数就整数部分加1
				if(pageIndex >= pageCount)
					opts.finished && opts.finished(pageIndex,pageCount);
				else
					$(obj).attr({'pageIndex':++pageIndex,'scrollPagination':'enabled'});
			};
			if(opts.beforeLoad && opts.beforeLoad(pageIndex,pageCount) === false) return;
			$(obj).attr('scrollPagination', 'disabled');


            var onDescCallBack = function(desc){
                if(opts.onDesc == null){
                    Result.alert( "对不起:" + desc );
                } else {
                    opts.onDesc(desc);
                }
            };
            var onErrorCallBack = function(err){
                if(opts.onError == null){
                    Result.alert( "错误:" + JSON.stringify(err));
                } else {
                    opts.onError(err);
                }
            };
            
            if(opts.postData){
                opts.postData.cPage = pageIndex;
                ResultProxy.doResult( {
                    url: url,
                    type: "POST",
                    async: false,
                    data : opts.postData
                }, function ( data) {
                    ajaxCallback(data);
                }, function ( desc ) {
                    onDescCallBack(desc);
                }, function ( err ) {
                    onErrorCallBack(err);
                } );
            } else {
                ResultProxy.doResult( {
                    url: url,
                    type: "GET",
                    async: false
                }, function ( data) {
                    ajaxCallback(data);
                }, function ( desc ) {
                    onDescCallBack(desc);
                }, function ( err ) {
                    onErrorCallBack(err);
                } );
            }
		}

	};

	$.fn.scrollPagination.init = function(obj, opts){
		var target = opts.scrollTarget;
		$(obj).attr({'scrollPagination':'enabled','pageIndex':opts.pageIndex,'totalItems':opts.totalItems});
		$(target).scroll(function(event){
			if ($(obj).attr('scrollPagination') == 'enabled')
				$.fn.scrollPagination.loadContent(obj, opts, false);
			else 
				event.stopPropagation();
		});
		
		$.fn.scrollPagination.loadContent(obj, opts, true);

	};

	$.fn.scrollPagination.defaults = {
		'url' : null,
		'postData' : null,
		'onError' : null,
        'onDesc' : null,
		'beforeLoad' : null,
		'afterLoad' : null,
		'finished' : null,
		'scrollTarget': window,
		'scrollPage': document,
		'pageIndex' : 1,
		'pageSize'  : 0,
		'totalItems': 0,
		'offset' : 0,
		'vertical' : true	  
	};


    var ResultProxy = ( function () {

        return {
            /**
             * 请求成功的resultCode编码
             */
            SUCCESS: "0",
            /**
             * 请求失败的resultCode编码
             */
            FAIL: "1",

            defaults: {
                ajax: {
                    setting: {
                        type: "POST",
                        async: true,
                        contentType: "application/x-www-form-urlencoded",
                        data: null,
                        url: null,
                        dataType: "text",
                        success: null,
                        error: null,
                        $mask: $( "body" ),
                        result: {
                            status: "code",
                            data: "data",
                            desc: "msg",
                            success: "0",
                            fail: "1",
                            stringifyOnPost: false
                        }
                    }
                }
            },
            /**
             * json字符串转json对象
             */
            jsonEval : ( function () {
                return String.prototype.parseJSON ?
                    function ( data ) {
                        return String.prototype.parseJSON.call( data );
                    } :
                    window.JSON ?
                        function ( data ) {
                            return JSON.parse( data );
                        } :
                        function ( data ) {
                            return eval( "(" + data + ")" );
                        }
            } () ),
            /**
             * 指定作用域和参数执行函数
             * @param func 待执行的函数
             * @param scope 指定的作用域
             */
            applyFunction: function ( func, scope ) {
                var args = [];
                Array.prototype.unshift.apply( args, arguments );
                if ( $.isFunction( func ) ) {
                    if ($.type( scope ) !== "object" ) {
                        scope = null;
                    }
                    Array.prototype.splice.call( args, 0, 2 );
                    func.apply( scope, args );
                }
            },
            /**
             * 执行ajax
             * @param opt
             */
            doAjax: function ( opt ) {
                opt = $.extend( true, {}, ResultProxy.defaults.ajax.setting, opt );
                if ( $.support && $.support.cors !== undefined ) {
                    $.support.cors = true;
                }
                $.ajax( opt );
            },
            /**
             * 执行特定返回值判定的ajax
             * @param opt
             * @param successCallback 成功回掉函数
             * @param failCallback 失败回掉函数
             * @param errorCallback 异常回掉函数
             */
            doResult: function ( opt, successCallback, failCallback, errorCallback ) {
            	//做加密
            	var timeStamp = new Date().getTime().toString();
            	var extParams = {};
            	extParams.sign = DES3.encrypt("x/fBeYXQ95Q+Aa7QGYVigzRD",hex_md5(timeStamp).toUpperCase());
            	extParams.timestamp =timeStamp;
            	var token =$.cookie(App.getCookieTokenEncrypt());
        		if(typeof(token) === "undefined" || token == null || token == "" || token == "null"){
        			//extParams.token = "";
        		} else {
        			extParams.token = token;
        		}
        		extParams.imsi = 'unkown';
        		extParams.imei = 'unkown';
        		extParams.system_type = '3';
        		extParams.client_version = 'unkown';
        		extParams.longitude = 'unkown';
        		extParams.latitude = 'unkown';
        		extParams.model = 'unkown';
        		extParams.channel_type = 'unkown';
        		extParams.system_version = 3;
        		opt.data = $.extend({}, opt.data, extParams);
            	
                opt = $.extend( true, {}, ResultProxy.defaults.ajax.setting, {
                    success: function ( response ) {
                        try {
                            var resJson = ResultProxy.jsonEval( response),
                                status = resJson[opt.result.status],
                                data = resJson[opt.result.data],
                                desc = resJson[opt.result.desc];
                            if ( status === opt.result.success ) {
                                ResultProxy.applyFunction( successCallback, null, data);
                            } else if ( status === opt.result.fail ) {
                                ResultProxy.applyFunction( failCallback, null, desc );
                            } else {
                            	console.log("错误返回码：" + status + ",错误信息: "+ desc);
                            	if(status == "1006"){ //token失效
                            		//跳转到登录
                            		alert("验证失效了，请重新登录");
                            		setTimeout(function () {
                            			window.location.href = App.loginUrl();
                        		    }, 2000);
                            		return;
                            	}
                                ResultProxy.applyFunction( failCallback, null, desc);
                            }
                        } catch ( e ) {
                            ResultProxy.applyFunction( errorCallback, null, e );
                        }
                        if( opt.$mask && $.fn.unmask ) {
                            opt.$mask.unmask();
                        }
                    },
                    error: function ( err ) {
                        ResultProxy.applyFunction( errorCallback, null, err );
                        if( opt.$mask && $.fn.unmask ) {
                            opt.$mask.unmask();
                        }
                    }
                }, opt );

                // stringify data on post if data is json
                if ( opt.result.stringifyOnPost === true && ( opt.type || "" ).toLowerCase() === "post" && $.type( opt.data ) === "object" ) {
                    opt.data = JSON.stringify( opt.data );
                }

                if( opt.$mask && $.fn.mask ) {
                    opt.$mask.mask();
                }
                if ( $.support && $.support.cors !== undefined ) {
                    $.support.cors = true;
                }
                $.ajax( opt );
            }
        };
    } () );



})( jQuery );